import { View, Text, RichText } from "@tarojs/components";
import Taro, { useLoad ,usePageScroll} from "@tarojs/taro";
import "./index.scss";
import { useState } from "react";
import { whRequest } from "@/utils/request";


export default function AgreeAgreement() {
  const [curCont, setCurCont] = useState("");
  const [canClick, setCanClick] = useState(false);
  const [btnTxt, setBtnTxt] = useState("同意");
  const [_windowHeight, _setWindowHeight] = useState(0);
  const [contentList, setContentList] = useState<any[]>([]);
  const [contHeight,setContHeight] = useState(0)
  const [curIndex, setCurIndex] = useState(0);

  function getAritcleDetail(articleIdList) {
    
    let reqArticleContentFn = articleIdList.map((articleId) => {
      return new Promise((resolve) => {
        whRequest({
          url: "/wcm/articles/" + articleId,
          method: "GET",
          responseType: "text",
          success: (data) => {
            console.log('getAritcleDetail data:', data)
            resolve({
              name: data.title,
              content: data.content.replace(
                /\<img/gi,
                '<img class="rich-img" style="width:750rpx;height:auto;display:block"'
              ),
            });
          },
        });
      });
    });
    console.log('reqArticleContentFn:',reqArticleContentFn)
    Promise.all(reqArticleContentFn).then((aRes: any) => {
      console.log('aRes:', aRes)
      aRes = aRes.filter((item) => {
        return !!item;
      });
      setContentList(aRes);
      setCurCont(aRes[0].content);
      Taro.setNavigationBarTitle({
        title: aRes[0].name,
      });
      setTimeout(() => [getContentHeight()], 200);
    });
  }
  function getContentHeight(){
    let query = Taro.createSelectorQuery()
    query
      .select('#cont')
      .boundingClientRect(function (rect:any) {
        // 多减去50,这样pagescroll 判断是不是到底部的时候，不用每次都减了
        setContHeight(rect.height - 50)
      })
      .exec()
  }
  

  function getNextAgreement() {
    if (!canClick) {
      return
    }
    // console.log('curIndex:', curIndex)
    // console.log('curIndex:',curIndex)
    if (curIndex < contentList.length - 1) {
      Taro.pageScrollTo({
        scrollTop: 0
      })
      setTimeout(() => {
        setCurIndex(curIndex + 1)
        setCurCont(contentList[curIndex + 1].content)
        setCanClick(false) 
        setBtnTxt('请向上滑动阅读到底部')
        
        Taro.setNavigationBarTitle({
          title: contentList[curIndex + 1].name
        })
        getContentHeight()
      }, 200)
    } else {
      // console.log('back')
      Taro.setStorageSync(
        'pages/agreeAgreement/index/agreeInsuranceAgreement',
        true
      )
      // wx.redirectTo({
      //   url: '/pagesIns/insurance/index'
      // });
      Taro.navigateBack({
        delta: 1
      })
    }
  }
  useLoad((options) => {
    console.log("Page loaded.options:",options);
    let articleIds = options.articleIds;
    let articleIdList = articleIds.split(",");
    if(articleIdList.length > 0){
      getAritcleDetail(articleIdList)
      // 获取当前window高度
      const res = Taro.getWindowInfo();
      _setWindowHeight(res.windowHeight);
    }else {
      Taro.showToast({
        title:'参数错误',
        icon: "none",
      })
    }
  
  });


  usePageScroll((res) => {
    
    if (res.scrollTop + _windowHeight > contHeight) {
      // console.log('滚动到底部了')
      setCanClick(true)
      setBtnTxt('同意')
    }

  })
  return (
    <View className="agreement">
      <RichText nodes={curCont} id="cont" className="cont"></RichText>
      <view
        className={["main-bottom-btn", canClick ? "" : "disabled"].join(" ")}
        onClick={getNextAgreement}
      >
        <view className="main-bottom-inner">{btnTxt}</view>
      </view>
    </View>
  );
}
